<?php
declare(strict_types=1);

namespace longbingcore\wxcore;


use app\Common\LongbingServiceNotice;

use app\shop\model\Express;
use think\facade\Db;

class Socket{



    public $socket = 0;

    //func
    public function listen($ip, $port)
    {

        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);


        socket_bind($this->socket, $ip, $port);


        $ex = socket_listen($this->socket, 4);
        //socket_bind($this->socket, '127.0.0.1', $port) or die("socket_bind() fail:" . socket_strerror(socket_last_error()) . "/n");
        //$ex = socket_listen($this->socket, 4) or die("socket_listen() fail:" . socket_strerror(socket_last_error()) . "/n");

        return $ex;
    }

    public function accept(){

        return socket_accept($this->socket);
    }


    public function close()
    {
        if($this->socket == 0) return;
        socket_close($this->socket);
        $this->socket = 0;
    }

    public function send_bytes($cs, $bytes)
    {
        $str = $this->bytes_to_string($arr);
        $ex = $this->send($cs, $str);
        return $ex;
    }

    public function recv_bytes($cs, $len = 1024)
    {
        $ret = $this->recv($cs, $len);
        $bytes = $this->string_to_bytes($ret);
        return $bytes;
    }

    public function send($cs, $msg)
    {
        $ex = socket_write($cs, $msg);
        return $ex;
    }

    public function recv($cs, $len = 1024)
    {
        $ret = socket_read($cs, $len);
        return $ret;
    }

    ///accessibility

    public function bytes_to_string($bytes)
    {
        $str = '';
        for($i=0; $i<count($bytes); $i++)
        {
            $str .= chr($bytes[$i]);
        }
        return $str;
    }

    public function string_to_bytes($str)
    {
        $bytes = array();
        for($i=0; $i<strlen($str); $i++)
        {
            $bytes[] = ord($str[$i]);
        }
        return $bytes;
    }


}